import React from 'react';
import { useEffect, useState } from 'react';
import { useHistory } from 'umi';

export default function Login() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const history = useHistory()

  useEffect(() => {
    fetch('/users')
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
      });
  }, []);

  return (
    <div>
      <input
        type="text"
        onChange={(event) => setUsername(event.target.value)}
      />
      <input
        type="password"
        onChange={(event) => setPassword(event.target.value)}
      />

      <button
        onClick={() =>
          fetch('/users/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password }),
          })
            .then((res) => res.json())
            .then((res) => {
              if(res.ok) {
                localStorage.setItem("token", username)
                history.push('/center')
              } else {
                alert("用户名密码不匹配")
              }
            })
        }
      >
        Login
      </button>
    </div>
  );
}
